package msearch.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import msearch.model.Mp3Object;

public class DBManager {

	private static final String userName = "root";
	
	private static final String passWord = "dbadmin";
	
	private static final String connectionUrl = "jdbc:mysql://localhost/test";
	
	
	private Connection getConnection(){
		Connection conn = null;
		try{
			Class.forName("org.gjt.mm.mysql.Driver");
			conn = DriverManager.getConnection(connectionUrl,userName,passWord);
		}catch(Exception  e){
			e.printStackTrace();
		}
		return conn;
	}
	
	public ResultSet search(String sql){
		ResultSet re = null;
		try {
			re = getConnection().createStatement().executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return re;
	}
	
	public boolean insertOrUpdate(String sql){
		int flag = -1;
		try {
			flag = getConnection().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(flag==-1){
			return false;
		}
		else{
			return true;
		}
	}
	
	public boolean insertOrUpdate(Mp3Object mobj){
		String sql = "insert into mp3(artist,name,album,publishdate,filePath) values('";
		sql+=mobj.getArtist()+"',"+"'"+mobj.getName()+"',"+"'"+mobj.getAlbum()+"',"+"'"+mobj.getPublishDate()+"',"+"'"+escape(mobj.getFilePath())+"')";
		return insertOrUpdate(sql);
	}
	public static String escape(String s){
		return s.replaceAll("\\\\", "\\\\\\\\");
//		return "";
	}
}
